'use strict'

import {
  app,
  protocol,
  BrowserWindow,
  ipcMain,
  dialog
} from 'electron'
import {
  createProtocol
} from 'vue-cli-plugin-electron-builder/lib'
import installExtension, {
  VUEJS3_DEVTOOLS
} from 'electron-devtools-installer'
const path = require('path');
const appFolder = path.dirname(process.execPath);
const updateExe = path.resolve(appFolder, "..", "Update.exe");
const exeName = path.basename(process.execPath);

const electron = require('electron');
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{
  scheme: 'app',
  privileges: {
    secure: true,
    standard: true
  }
}])
var win

//用一个 Tray 来表示一个图标,这个图标处于正在运行的系统的通知区 ，通常被添加到一个 context menu 上.
const Menu = electron.Menu;
const Tray = electron.Tray;
var appTray


var q = require('qiao-is-online');
var timeFT = require('time-format-tools');
// var onLine = null;
var id_onlineIterator

async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 543,
    height: 360,
    // width: 800,
    // height: 600,
    show:false,
    icon:path.join(__static, 'app.ico'),
    // 隐藏菜单栏
    autoHideMenuBar: true,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false
    }
  })

  win.on('close', (e) => {
    console.log("close")
    e.preventDefault();
    win.isVisible() ? win.hide() : win.show();
  //   dialog.showMessageBox({
  //     title: "退出",//信息提示框标题
  //     message: "彻底退出程序还是将程序放置在后台执行",//信息提示框内容
  //     buttons: ["彻底退出程序", "放置在后台"],//下方显示的按钮
  //     noLink:true, //win下的样式
  //     type: "error",//图标类型
  //     //type: "info",//图标类型
  //     //icon:nativeImage.createFromPath("./icon/png.png"),//图标
  //     cancelId:2//点击x号关闭返回值
  //   }).then((index) => {
  //     console.log(index)
  //     if (index.response === 0) {
  //       console.log("关闭")
  //       app.exit();
  //     }else if(index.response === 1){
  //       console.log("阻止关闭")
  //       e.preventDefault();
  //       win.isVisible() ? win.hide() : win.show();
  //     }else{
  //       e.preventDefault();
  //     }
  // });

    // dialog.showMessageBox({
    //   type: 'info',
    //   title: 'Information',
    //   message: 'Do you really want to close the application?',
    //   buttons: ['Yes', 'No'],
    //   cancelId:2
    // },function(index){
    //   console.log("index="+index)
    // })
  });
  // (index) => {
  //   console.log("关闭拦截"+index)
  //   if (index === 0) {
  //     win = null;
  //     // app.quit();不要用quit()，会弹两次
  //     app.exit();
  //   } else {
  //     e.preventDefault(); //阻止默认行为
  //   }
  // }
  //系统托盘右键菜单
  var trayMenuTemplate = [{
      label: '打开主页面',
      click: function () {
        win.isVisible() ? win.hide() : win.show();
      }
    },
    {
      label: '退出程序',
      click: function () {
        console.log("退出程序")
        app.exit();
      }
    }
  ];

  //系统托盘图标目录
  // var trayIcon = path.join(__dirname, 'icon');
  appTray = new Tray(path.join(__static, 'app.ico'));
  console.log("生成tray图标")
  //图标的上下文菜单
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  //设置此托盘图标的悬停提示内容
  appTray.setToolTip('ISIP联网程序');
  //设置此图标的上下文菜单
  appTray.setContextMenu(contextMenu);




  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  console.log("window-all-closed")
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()

  }
})



//=============主要代码=================
const isFirstInstance = app.requestSingleInstanceLock()
 
if (!isFirstInstance) {
  console.log('is second instance')
  app.exit();
} else {
  app.on('second-instance', (event, commanLine, workingDirectory) => {
    console.log('new app started', commanLine)
    // if (win) {
    //   con
    // }
  })

  app.on('ready', async () => {

    // if(!isDevelopment){
    //   app.setLoginItemSettings({
    //     openAtLogin: true,
    //     openAsHidden: true,
    //     path: ex,
    //     args: []
    //   });
    // }
  
    id_onlineIterator = setTimeout(function(){
      onlineIterator()
    }, 3 * 1000);
    createWindow()
    if (isDevelopment && !process.env.IS_TEST) {
      // Install Vue Devtools
      try {
        await installExtension(VUEJS3_DEVTOOLS)
      } catch (e) {
        console.error('Vue Devtools failed to install:', e.toString())
      }
    }
  })
  
  // Exit cleanly on request from parent process in development mode.
  if (isDevelopment) {
    if (process.platform === 'win32') {
      process.on('message', (data) => {
        if (data === 'graceful-exit') {
          app.quit()
        }
      })
    } else {
      process.on('SIGTERM', () => {
        app.quit()
      })
    }
  }


}
//========================================
 


app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.


ipcMain.on("send-message-to-main", (event, args) => {
  console.log("主进程接受到的数据是:", args);
  if (args.indexOf("ISIP") != -1) {
    var cmdStr = "netsh wlan connect name=\"" + args + "\""
    cmdStart(cmdStr)
  }
  // event.reply("send-message-to-cli","这是来自主进程的问候");
  // win.webContents.send("send-message-to-cli","我是主进程，主动和你通信")
})
// win.webContents.send("send-message-to-cli","我是主进程，主动和你通信")


// 获取可执行文件位置
const ex = process.execPath;

// 定义事件，渲染进程中直接使用


// 开机自启动设置
ipcMain.on('openAutoStart', (event,state) => {
  console.log("设置开机自启 "+state)
  if(!isDevelopment){
  app.setLoginItemSettings({
    openAtLogin: state,
    path: ex,
    args: []
  });
}
})

function cmdStrReturn(re) {
  console.log(re)
  if (re.indexOf("成功") != -1)
    win.webContents.send("send-message-to-cli", "ok")
  else win.webContents.send("send-message-to-cli", "fali")
}

function cmdStart(cmdStr) {
  console.log("执行系统命令")
  var iconv = require('iconv-lite');
  var encoding = 'cp936';
  var binaryEncoding = 'binary';
  var exec = require("child_process").exec;
  exec(cmdStr, {
    encoding: binaryEncoding
  }, function (err, stdout, stderr) {
    if (err) {
      console.log("get weather api error:" + stderr);
    } else {
      // console.log(stdout);
      var co = iconv.decode(new Buffer(stdout, binaryEncoding), encoding)
      console.log(co)
      cmdStrReturn(co)
    }
  });
}
function getFormatTime() {
  return timeFT('YYYY-MM-DD hh:mm:ss');
}

function onlineIterator() {
  // try-cache 对错误进行捕获
  try {
      // 获取 async 方法返回的 Promise 值赋予 isOnline
      var isOnline = q.isOnline();
      // 由于 async 方法返回的内容在 Promise 值内的为 PromiseResult ，
      // 不使用 async/await 等一般无法取出，将和 PromiseResult 有关的逻辑包含在 Promise.then() 函数内
      isOnline.then(function(result) {
          // 初始化局部变量，与全局变量 onLine 不同，在函数递归的过程中，局部变量的值不会继承
          // let flag = false;
          // // 判断 PromiseResult 的值
          // if (result === 'online') {
          //     flag = true;
          // }
          console.log("网络状况："+result)
          if(result !== 'online'){
            win.webContents.send("send-message-to-cli", "post")
            console.log("连接网络")
          }
          // 判断互联网连接情况是否发生变化，变化则通知
          // if (onLine != flag) {
          //     // 变更本次互联网连接情况
          //     onLine = flag;

          //     // 设置通知信息
          //     if (onLine == true) {
          //       // 弹出底部通知消息
          //     console.log("网络恢复");
          //         flag = "online" + " " + getFormatTime();
          //     } else {
          //     console.log("网络断开");
          //         flag = "offline" + " " + getFormatTime();
          //         win.webContents.send("send-message-to-cli", "post")
          //     }
              
          // }
          // 释放局部变量引用，脱离执行环境，在下一次垃圾收集器执行操作时被找到并释放。
          // flag = null;
      });
      // 在继续递归调用之前，通过 setTimeout() 返回的 id 释放原句柄，防止堆栈溢出
      clearTimeout(id_onlineIterator);

      id_onlineIterator = null;
      // 继续递归
      id_onlineIterator = setTimeout(function(){
        onlineIterator()
      }, 10 * 1000);
  } catch (e) {
      console.log("[Network] error" + " " + getFormatTime());
      console.log(e);
      // 通过 setTimeout() 返回的 id ，结束递归
      clearTimeout(id_onlineIterator);
      id_onlineIterator = null;
  }
}